﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DataAcquisition;
using DataAcquisition.TransferObjects;
using DataAnalysis.Filter;
using DataAnalysis;

namespace tpu_bci
{
    public partial class VEPControlForm : Form
    {
        private const int MinAmplitude = 5;

        private const int MaxAmplitude = 15;

        private const int WindowSize = 200;

        private EegReceiver eegReceiver;
        private VisualFilter visualFilter;

        private EegDataHolder eegDataHolder;


        public VEPControlForm()
        {
            InitializeComponent();

            eegReceiver = new EegReceiver();
            eegReceiver.ProcessEegData = ProcessEegData;

            visualFilter = new VisualFilter();

            eegDataHolder = new EegDataHolder();           
        }

        private void ProcessEegData(EegData eegData)
        {
             eegDataHolder.Push(eegData.Data);

             if (eegDataHolder.HasData(WindowSize))
             {
                 List<float[]> data = eegDataHolder.GetData(WindowSize);
                 float[] filtered = visualFilter.Filter(data);
                 float amplitude = StatisticsUtil.GetAverageAmplitude(filtered);
                 DrawAmplitude(amplitude);
             }          
        }

        private void DrawAmplitude(float amplitude)
        {
            this.powerPanel.Invoke((Action)delegate()
            {

                float part = (amplitude - MinAmplitude) / (MaxAmplitude - MinAmplitude);
                float signalHeight = part * this.powerPanel.Height;              
               
                float amplitudePoint = this.powerPanel.Height - signalHeight;

                Graphics graphics = this.powerPanel.CreateGraphics();

                graphics.FillRectangle(Brushes.White, 0, 0, this.powerPanel.Width, this.powerPanel.Height);

                graphics.FillRectangle(Brushes.DarkRed, 0, amplitudePoint, this.powerPanel.Width, signalHeight);
            
            });
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            try
            {
                eegReceiver.StartReceiving();
                startButton.Enabled = false;
            }
            catch (Exception)
            {
                 MessageBox.Show("Аппаратные проблемы с устройством ЭЭГ");
                //return;
            }
        }
    }
}
